package net.xinqushi.collection;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author xjie 2019/7/29 14:26
 * @description  常见的List使用错误
 */
public class CommonErrors {

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(1);list.add(2);list.add(3);list.add(4);list.add(5);list.add(6);
        for(int i = 0 ; i < list.size() ; i ++){ // IndexOutOfBoundsException , 错误结果
            System.out.println(list.get(i));
            list.remove(i);
        }
        for (Integer i :list) { // iterator , ConcurrentModificationException , fail-fast
            System.out.println(i);
            list.remove(i);
        }
        Iterator<Integer> iterator = list.iterator();
        while (iterator.hasNext()){ // 正确移除 并遍历
            System.out.println(iterator.next());
            iterator.remove();
        }
        list.forEach((item)->{ //未发现移除方式
            System.out.println(item);
        });
    }
}
